class UsersController < ApplicationController
    before_filter :require_project_manager, :only=>[:index,:new]

    def index
      if current_user.role_id==1
        @users=User.find :all
      else
        @users=User.find :all,:conditions=>'role_id!=1 and role_id!=2'
      end
    end

  
    def edit
       @user = current_user unless current_user.role_id==1 && @user=User.find(params[:id]);
    rescue
      flash[:notice] = "Usuario no existente"
      redirect_to :controller=>'login'
    end


      def update

      unless params['commit']=="Guardar"
        redirect_to( :controller => 'users' )
        return false
      end

      @user = User.find(params[:id])

      params[:user][ :role_id ] = ( (current_user.role_id==1) ? (params[:user][ :role_id ]) : current_user.role_id )

      if @user.update_attributes( params[:user] )
        flash[:notice] = "Usuario actualizado satisfactoriamente"
        redirect_to :controller => 'users'
      else
        render :action => 'edit'
      end

    end



  def new
      @user = User.new
  end


  def create  
     @user = User.new(params[:user])

      unless params['commit']=="Guardar"
        redirect_to( :controller => 'users' )
        return false
      end

     if @user.save  
       flash[:notice] = "Usuario registrado correctamente."
       redirect_to :controller=>'users'
     else  
       render :action => 'new'  
     end  
  end

  def destroy
         @user = User.find(params[:id])

         @user.projects.each{ |x|
           x.destroy
         }

         @user.tasks.each{ |x|
            x.week_time_sheets.each{  |y|
              y.destroy
            }
           x.destroy

         }
         
         @user.destroy
         flash['notice']="usuario eliminado"
         redirect_to :controller=>'users'
  end

end
